import React, { Component } from 'react';
import { Button, Form, Input, message, Modal } from 'antd';
import { messages } from 'share/common';
import CustomReportService from './custom-report/custom-report.service';
import InputLanguage from 'components/template/input-language';
import Chooser from 'components/chooser';
import SingleFieldCompOtherData from 'containers/data-center/report-management/single-field-comp-other-data';
const FormItem = Form.Item;

@Form.create()

class EditCustomDataModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        i18n: {},
        reportType: 'SDRM',
        reportModelDetails: []
      },
      visibleModal: false,
      loading: false,
      currentMainReport: {}
    }
  }

  componentWillMount() {

  }

  componentDidMount() {
    const { params } = this.props;
    if (params.id && params.id !== 'new') {
      this.setState({loading: true})
      CustomReportService.getSingleCustomModalDetail({reportId: params.id}).then((res)=>{
        if (res.status === 200) {
          this.setState({
            data: res.data,
            loading: false,
            currentMainReport: {id: res.data.masterReportId, reportName: res.data.masterReportName}
          })
        }
      }).catch(()=>{this.setState({loading: false})})
    }
  }

  componentWillUnmount() {

  }

  save = (e) => {
    e.preventDefault();
    const { data } = this.state;
    let isNew = !!data.id;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({loading: true});
        data.reportName = values.reportName.name;
        data.reportDesc = values.reportDesc.name;
        data.i18n['reportName'] = values.reportName.i18n;
        data.i18n['reportDesc'] = values.reportDesc.i18n;
        data.masterReportId = values.masterReportId[0].id;
        data.masterReportName = values.masterReportId[0].reportName;
        data.reportModelDetails = values.reportModelDetails;
        CustomReportService.newOrUpdateCustomModal(data).then((res)=>{
          if (res.status === 200) {
            this.setState({loading: false})
            message.success(isNew ? messages('basic-10.key107')/*保存成功*/ : messages('basic-10.key237')/*新建成功*/);
            this.props.close({needRefresh: true, key: 'modal'});
          } else {this.setState({loading: false})}
        }).catch(()=>{this.setState({loading: false})})
      }
    });
  }

  mainReportChange = (e) => {
    const { currentMainReport = {} } = this.state;
    let idDoseNotMatch, oneToNone;
    if (e && e.length) {
      if (!(e[0].id === currentMainReport.id) && !!currentMainReport.id)
        idDoseNotMatch = true;
    } else {
      if (currentMainReport.id)
        oneToNone = true;
    }
    let listHasData = !!this.props.form.getFieldValue('reportModelDetails').length;
    if ( ((idDoseNotMatch && listHasData) || (oneToNone && listHasData)) ) {
       Modal.confirm({
         title: messages('basic-10.key238')/*切换主表会清空数据附表，是否切换？*/,
         okText: messages('basic-10.key239')/*切换*/,
         cancelText: messages('common.cancel')/*取消*/,
         onOk: () => {
           this.setState({currentMainReport: e[0]});
           this.props.form.setFieldsValue({ 'reportModelDetails': [] })
         },
         onCancel: ()=>{
           this.props.form.setFieldsValue({ 'masterReportId': [currentMainReport] })
         }
       })
    } else {
      this.setState({currentMainReport: e[0]});
    }
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, data, currentMainReport } = this.state;
    return (
      <div className='edit-custom-data-modal'>
        <Form className='new-form' onSubmit={this.save}>
          <FormItem required label={messages('basic-10.key199')/*模型名称*/}>
            {getFieldDecorator('reportName', {
              rules: [InputLanguage.required],
              initialValue: { name: data.reportName, i18n: data.i18n ? data.i18n.reportName : [] }
            })(
              <InputLanguage
                placeholder={messages('common.max.characters.length',{arg1: 50})/*最多输入{arg1}个字符*/}
                maxLength={50}
              />
            )}
          </FormItem>
          <FormItem required label={messages('basic-10.key200')/*模型分类*/}>
            <Input value={messages('basic-10.key235')/*自定义数据模型*/} disabled />
          </FormItem>
          <FormItem required label={messages('basic-10.key201')/*模型描述*/}>
            {getFieldDecorator('reportDesc', {
              rules: [InputLanguage.required],
              initialValue: { name: data.reportDesc, i18n: data.i18n ? data.i18n.reportDesc : [] }
            })(
              <InputLanguage
                placeholder={messages('common.max.characters.length',{arg1: 100})/*最多输入{arg1}个字符*/}
                maxLength={100}
              />
            )}
          </FormItem>
          <FormItem required label={messages('basic-10.key202')/*数据主表*/}>
            {getFieldDecorator('masterReportId', {
              rules: [
                {
                  required: true,
                  message: messages('common.select')/*请选择*/
                }
              ],
              initialValue: data.masterReportId ? [{id: data.masterReportId, reportName: data.masterReportName}] : []
            })(
              <Chooser
                type={'system-data-modal-list'}
                labelKey='reportName'
                valueKey='id'
                listExtraParams={{reportType: 'I'}}
                onChange={this.mainReportChange}
                showNumber={false}
                single={true}
              />
            )
            }
          </FormItem>
          <FormItem>
            {getFieldDecorator("reportModelDetails", {
              initialValue: data.reportModelDetails || []
            })(
              <SingleFieldCompOtherData
                onRef={ref=> this.SingleFieldCompRef = ref}
                currentMainReport={currentMainReport}
              />
            )}
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>
              {messages('common.save')/*保存*/}
            </Button>
            <Button onClick={() => {
              this.props.close({needRefresh: false});
            }}>
              {messages('common.cancel')/*取消*/}
            </Button>
          </div>
        </Form>
      </div>
    );
  }
}

EditCustomDataModal.propTypes = {};

export default EditCustomDataModal;
